package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @PackageName: com.itheima.filter
 * @ClassName: LoginCheckFilter
 * @Description:
 * @Author: zhangcheng
 * @DateTime: 2022/6/6 17:01
 * @Version 1.0
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}", requestURI);
        //定义需要放行的地址
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断本次请求是否要放行
        boolean check = check(loginUrls, requestURI);
        //url可以直接放行
        if (check) {
            log.info("本次请求:{}不需要处理,直接放行", loginUrls);
            filterChain.doFilter(request, response);
            return;
        }
        //判断登录状态(session中是否有数据)
        Object id = request.getSession().getAttribute("employee");

        if (id != null) {
            log.info("用户已登录,id为: ", id);

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            return;
        }

        User user = (User) request.getSession().getAttribute("user");
        if (user != null){
            BaseContext.setCurrentId(user.getId());
            filterChain.doFilter(request,response);
            BaseContext.remove();
            return;
        }


            //用户未登录
            log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    private boolean check(String[] loginUrls, String requestURI) {
        for (String loginUrl : loginUrls) {
            boolean match = PATH_MATCHER.match(loginUrl, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
